package com.nzw.security.filter;

import com.nzw.redis.impl.common.RedisTemplate;
import com.nzw.utils.ServletUtil;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PassThruFilter extends PassThruAuthenticationFilter {
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        Subject subject = getSubject(httpRequest, httpResponse);
        if (subject.isAuthenticated()) {
            return super.onAccessDenied(request, response);
        } else {
            if (ServletUtil.isAjaxRequest(httpRequest)) {
                WebUtils.toHttp(httpResponse).sendError(401);
                return false;
            }
            return super.onAccessDenied(request, response);
        }
    }


}
